var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const axios = require('axios');
const { Store, User } = require('../model/model');

// JWT密钥
const JWT_SECRET = 'rbac-system-secret-key';

// 验证Token中间件
const authMiddleware = (req, res, next) => {
  const token = req.header('x-auth-token');
  if (!token) {
    return res.status(401).json({ code: 401, message: '无访问权限，请先登录' });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ code: 401, message: '无效的Token' });
  }
};

// 获取门店列表（支持搜索和分页）
router.get('/stores', authMiddleware, async (req, res) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      search = '', 
      status = '' 
    } = req.query;

    // 构建查询条件
    const query = {};
    
    // 搜索条件
    if (search) {
      query.$or = [
        { name: { $regex: search, $options: 'i' } },
        { address: { $regex: search, $options: 'i' } },
        { manager: { $regex: search, $options: 'i' } },
        { phone: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 状态筛选
    if (status) {
      query.status = status;
    }

    // 计算分页
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    // 查询数据
    const stores = await Store.find(query)
      .sort({ createTime: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    // 为每个门店计算员工数
    const storesWithStaffCount = await Promise.all(stores.map(async (store) => {
      const staffCount = await User.countDocuments({ store: store._id });
      return {
        ...store.toObject(),
        staffCount
      };
    }));
    
    // 查询总数
    const total = await Store.countDocuments(query);
    
    // 计算总页数
    const totalPages = Math.ceil(total / parseInt(limit));

    res.json({
      code: 200,
      message: '获取门店列表成功',
      data: {
        stores: storesWithStaffCount,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total,
          totalPages
        }
      }
    });
  } catch (error) {
    console.error('获取门店列表失败:', error);
    res.status(500).json({ 
      code: 500, 
      message: '获取门店列表失败', 
      error: error.message 
    });
  }
});

// 获取门店详情
router.get('/stores/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    
    const store = await Store.findById(id);
    if (!store) {
      return res.status(404).json({ 
        code: 404, 
        message: '门店不存在' 
      });
    }

    // 计算该门店的员工数
    const staffCount = await User.countDocuments({ store: store._id });

    res.json({
      code: 200,
      message: '获取门店详情成功',
      data: {
        ...store.toObject(),
        staffCount
      }
    });
  } catch (error) {
    console.error('获取门店详情失败:', error);
    res.status(500).json({ 
      code: 500, 
      message: '获取门店详情失败', 
      error: error.message 
    });
  }
});

// 创建门店
router.post('/stores', authMiddleware, async (req, res) => {
  try {
    const {
      name,
      address,
      phone,
      manager,
      status = '营业中',
      businessHours = '09:00-21:00',
      description = '',
      latitude,
      longitude
    } = req.body;

    // 验证必填字段
    if (!name || !address || !phone || !manager) {
      return res.status(400).json({
        code: 400,
        message: '门店名称、地址、电话、店长为必填项'
      });
    }

    // 检查门店名称是否重复
    const existingStore = await Store.findOne({ name });
    if (existingStore) {
      return res.status(400).json({
        code: 400,
        message: '门店名称已存在'
      });
    }

    // 创建新门店
    const newStore = new Store({
      name,
      address,
      phone,
      manager,
      status,
      businessHours,
      description,
      latitude,
      longitude
    });

    await newStore.save();

    res.status(201).json({
      code: 201,
      message: '门店创建成功',
      data: newStore
    });
  } catch (error) {
    console.error('创建门店失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建门店失败',
      error: error.message
    });
  }
});

// 更新门店
router.put('/stores/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 检查门店是否存在
    const existingStore = await Store.findById(id);
    if (!existingStore) {
      return res.status(404).json({
        code: 404,
        message: '门店不存在'
      });
    }

    // 如果更新门店名称，检查是否与其他门店重复
    if (updateData.name && updateData.name !== existingStore.name) {
      const duplicateStore = await Store.findOne({ 
        name: updateData.name, 
        _id: { $ne: id } 
      });
      if (duplicateStore) {
        return res.status(400).json({
          code: 400,
          message: '门店名称已存在'
        });
      }
    }

    // 更新时间
    updateData.updateTime = new Date();

    // 更新门店
    const updatedStore = await Store.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    );

    res.json({
      code: 200,
      message: '门店更新成功',
      data: updatedStore
    });
  } catch (error) {
    console.error('更新门店失败:', error);
    res.status(500).json({
      code: 500,
      message: '更新门店失败',
      error: error.message
    });
  }
});

// 删除门店
router.delete('/stores/:id', authMiddleware, async (req, res) => {
  try {
    const { id } = req.params;
    
    const store = await Store.findById(id);
    if (!store) {
      return res.status(404).json({
        code: 404,
        message: '门店不存在'
      });
    }

    await Store.findByIdAndDelete(id);

    res.json({
      code: 200,
      message: '门店删除成功'
    });
  } catch (error) {
    console.error('删除门店失败:', error);
    res.status(500).json({
      code: 500,
      message: '删除门店失败',
      error: error.message
    });
  }
});

// 重新统计并持久化各门店员工数
router.post('/stores/recalculate-staff-counts', authMiddleware, async (req, res) => {
  try {
    const stores = await Store.find({});

    let updated = 0;
    for (const store of stores) {
      const staffCount = await User.countDocuments({ store: store._id });
      // 将统计结果持久化到门店文档（兼容旧字段使用场景）
      await Store.findByIdAndUpdate(
        store._id,
        { staffCount, updateTime: new Date() },
        { new: true }
      );
      updated += 1;
    }

    res.json({
      code: 200,
      message: `员工数统计完成，共更新 ${updated} 家门店`,
      data: { updated }
    });
  } catch (error) {
    console.error('重新统计员工数失败:', error);
    res.status(500).json({
      code: 500,
      message: '重新统计员工数失败',
      error: error.message
    });
  }
});

// 批量删除门店
router.delete('/stores', authMiddleware, async (req, res) => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请提供要删除的门店ID列表'
      });
    }

    // 删除门店
    const result = await Store.deleteMany({ _id: { $in: ids } });

    res.json({
      code: 200,
      message: `成功删除 ${result.deletedCount} 个门店`,
      data: {
        deletedCount: result.deletedCount,
        ids
      }
    });
  } catch (error) {
    console.error('批量删除门店失败:', error);
    res.status(500).json({
      code: 500,
      message: '批量删除门店失败',
      error: error.message
    });
  }
});

// 获取门店统计信息
router.get('/stores/stats', authMiddleware, async (req, res) => {
  try {
    const total = await Store.countDocuments();
    
    // 按状态统计
    const statusStats = await Store.aggregate([
      {
        $group: {
          _id: '$status',
          count: { $sum: 1 }
        }
      }
    ]);

    // 员工总数
    const totalStaff = await Store.aggregate([
      {
        $group: {
          _id: null,
          total: { $sum: '$staffCount' }
        }
      }
    ]);

    // 平均员工数
    const averageStaff = total > 0 ? Math.round(totalStaff[0]?.total / total) : 0;

    res.json({
      code: 200,
      message: '获取统计信息成功',
      data: {
        total,
        statusStats: statusStats.reduce((acc, item) => {
          acc[item._id] = item.count;
          return acc;
        }, {}),
        totalStaff: totalStaff[0]?.total || 0,
        averageStaff
      }
    });
  } catch (error) {
    console.error('获取统计信息失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取统计信息失败',
      error: error.message
    });
  }
});

// 验证门店名称
router.get('/stores/validate/name', authMiddleware, async (req, res) => {
  try {
    const { name, excludeId } = req.query;

    if (!name) {
      return res.status(400).json({
        code: 400,
        message: '请提供门店名称'
      });
    }

    const query = { name };
    if (excludeId) {
      query._id = { $ne: excludeId };
    }

    const existingStore = await Store.findOne(query);
    const isValid = !existingStore;

    res.json({
      code: 200,
      message: '验证完成',
      data: {
        isValid,
        message: isValid ? '门店名称可用' : '门店名称已存在'
      }
    });
  } catch (error) {
    console.error('验证门店名称失败:', error);
    res.status(500).json({
      code: 500,
      message: '验证门店名称失败',
      error: error.message
    });
  }
});


module.exports = router; 